#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/wait.h>

int main(){
    int pid;
    char buff1[1024];
    char buff2[1024];
    int epfd1[2];
    int epfd2[2];
    //创建管道，epfd1[0]被初始化为读端,
    //efpd1[1]被初始化为写端
    int res = pipe(epfd1);
    if(res == -1){
        perror("pipe");
        exit(1);
    }

    res = pipe(epfd2);
    if(res == -1){
        perror("pipe");
        exit(1);
    }

    pid =  fork();
    if(pid == -1){
        perror("fork");
        exit(1);
    }
    //子进程
    if(pid == 0){
        char* msg = "I am child process\n";
        strncpy(buff1,msg, strlen(msg));
        buff1[strlen(msg)] = '\0';
        //通过epfd1写端发送给对方
        write(epfd1[1],buff1, 1024);
        char msg2[1024];
        //通过epfd2读端读取数据
        read(epfd2[0],msg2, 1024);
        printf("receive msg is %s\n", msg2);
        exit(0);
    }

    if(pid > 0){
        char* msg = "I am parent process\n";
        strncpy(buff2,msg, strlen(msg));
        buff2[strlen(msg)] = '\0';
        //通过epfd2写端发送给对方
        write(epfd2[1], buff2, 1024);
        char msg2[1024];
        //通过epfd1读端读取数据
        read(epfd1[0],msg2, 1024);
        printf("receive msg is %s", msg2);
        wait(NULL);
    }

    return 0;
}